#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "comm.h"

int main(int argc, char *argv[])
{
	if(argc != 2)
	{
		printf("usage: %s ipaddr\n", argv[0]);
		return -1;
	}

	int socket_fd;
	int ret;
	char buf[1024] = {0};
	char response[1024] = {0};
	struct sockaddr_in server_addr;

	// 创建套接字
	socket_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(socket_fd < 0)
	{
		perror("socket failed");
		return -1;
	}

	// 初始化服务器地址
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	server_addr.sin_port = htons(POP3_PORT);

	// 连接服务器
	ret = connect(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr));
	if(ret < 0)
	{
		perror("connect failed");
		return -1;
	}
	printf("Connected to POP3 server\n");
	printf("Please input commands(type 'quit' to exit):\n");

	while(1)
	{
		// 接收服务器消息
		memset(response, 0, sizeof(response));
		ret = recv(socket_fd, response, sizeof(response) - 1, 0);
		if(ret < 0)
		{
			perror("recv failed");
			break;
		}
		printf("%s", response);
			
		// 获取用户输入
		printf("> ");
		memset(buf, 0, sizeof(buf));
		fgets(buf, sizeof(buf) - 1, stdin);
		if(strncasecmp(buf, "quit", 4) == 0)
		{
			send(socket_fd, "quit\r\n", 6, 0);
			memset(response, 0, sizeof(response));
			recv(socket_fd, response, sizeof(response) - 1, 0);
			printf("Server response:\n%s", response);
			break;
		}
		else if(strncmp(buf, ".", 1) == 0)
		{
			send(socket_fd, ".\r\n", 3, 0);
			continue;
		}

		// 发送用户命令
		ret = send(socket_fd, buf, strlen(buf), 0);
		if(ret < 0)
		{
			perror("send failed");
			break;
		}
	}

	close(socket_fd);
	return 0;
}
